package com.dz.risk.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author Doke
 * @date 2021/7/1 14:49
 */
public class ResponseUtils {

    /**
     * 根据响应体获取输出流并设置文件格式
     * @param response 响应体
     * @param fileName 文件名(后缀会自动加上时间戳)
     * @return 输出流
     */
    public static ServletOutputStream getOutputStreamAndSettingFileFormat(HttpServletResponse response, String fileName) throws IOException {
        Assert.notNull(response, "响应体不能为空");
        Assert.notNull(fileName, "文件名不能为空");

        String newFileName = String.format(fileName, System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(newFileName, "UTF-8"));
        return response.getOutputStream();
    }

    /**
     * 设置输出信息
     * @param response     响应体
     * @param commonResult 返回信息
     */
    public static void out(HttpServletResponse response, Object commonResult) {
        ObjectMapper mapper = new ObjectMapper();
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            mapper.writeValue(response.getWriter(), commonResult);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
